<template>
  <div class="my-collection">
    <!-- 面包屑 -->
    <div class="container">
      <div class="breadcrumb">
        <router-link to="/">首页</router-link>
        <span class="sep">›</span>
        <router-link to="/user-center">个人中心</router-link>
        <span class="sep">›</span>
        <span>我的收藏</span>
      </div>

      <div class="layout">
        <!-- 右侧列表 -->
        <section class="collection-content">
          <!-- 用户信息与收藏统计 -->
          <div class="user-collection-header">
  <div class="user-info">
    <img
      :src="userProfile?.head_image"
      class="avatar-circle"
      alt="用户头像"
    >
    <div class="user-details">
      <h3 class="user-name">{{ userProfile?.username || '未登录用户' }}</h3>
    </div>
  </div>
  <div class="collection-stats">
    <div class="stat-item">
      <span class="stat-number">{{ totalCollections }}</span>
      <span class="stat-label">收藏总数</span>
    </div>
    <div class="stat-item">
      <span class="stat-number">{{ purchasedCount }}</span>
      <span class="stat-label">已购买</span>
    </div>
    <div class="stat-item">
      <span class="stat-number">{{ unpurchasedCount }}</span>
      <span class="stat-label">未购买</span>
    </div>
  </div>
</div>

          <!-- 筛选区域 -->
          <div class="filter-area">
            <span class="filter-label">筛选：</span>
            <div class="filter-buttons">
              <button
                class="filter-btn"
                :class="{ active: activeFilter === 'all' }"
                @click="handleFilter('all')"
              >
                全部收藏
              </button>
              <button
                class="filter-btn"
                :class="{ active: activeFilter === 'coffeeBeans' }"
                @click="handleFilter('coffeeBeans')"
              >
                咖啡豆
              </button>
              <button
                class="filter-btn"
                :class="{ active: activeFilter === 'coffeeTools' }"
                @click="handleFilter('coffeeTools')"
              >
                咖啡周边
              </button>
            </div>
            <button class="clear-all-btn" @click="clearAllCollections">
              <i class="fa fa-trash-o"></i> 清空全部
            </button>
          </div>

          <!-- 收藏列表 -->
          <div class="collections-grid">
            <div
              v-for="(item) in collections"
              :key="item.id"
                class="collection-card"
            >
              <div class="card-image">
                <img
        :src="item.image_urls && item.image_urls.length > 0
          ? (item.image_urls.startsWith('http') ? item.image_urls: `http://127.0.0.1:8000/static/${item.image_urls}`)
          : ''"
        :alt="item.name"
      />
                <button class="wish-btn" @click="cancelCollection(item)">
                  <i class="fa fa-heart"></i>
                </button>
              </div>
              <div class="card-info">
                  <router-link :to="'/productdetail?id=' + item.id" target="_blank">
                  <div class="name">{{ item.name }}</div>
                  </router-link>
                <p class="collection-desc">{{ item.desc }}</p>
                      <div class="price-area">
        <span class="now-price">¥{{ item.price.toFixed(2) }}</span>
        <span v-if="item.original_price" class="old-price">¥{{ item.original_price.toFixed(2) }}</span>
      </div>
                <button class="cart-btn" @click="addToCart(item)">加入购物车</button>
              </div>
            </div>

            <div class="empty-tip" v-if="filteredCollections.length === 0">
              暂无收藏内容
            </div>
          </div>

          <!-- 分页 -->
          <div class="pagination">
    <button class="pagination-btn" @click="prevPage">
      <i class="arrow-icon">&lt;</i>
    </button>
    <button
      v-for="page in totalPages"
      :key="page"
      class="pagination-btn"
      :class="{ 'active': currentPage === page }"
      @click="goToPage(page)"
    >
      {{ page }}
    </button>
    <button class="pagination-btn" @click="nextPage">
      <i class="arrow-icon">&gt;</i>
    </button>
  </div>
        </section>
      </div>
    </div>
    <BackTop :visible="showTop" @click="toTop" />
    <Footer />
  </div>
</template>
<script>
import Header from "@/components/Header.vue";
import Footer from "@/components/Footer.vue";
import BackTop from "@/components/BackTop.vue";
import api from '@/api/request'

export default {
  name: "MyCollection",
  components: { Header, Footer, BackTop },
  data() {
    return {
      showTop: false,
      activeFilter: "all", // 当前激活的筛选条件
    // 前端筛选标识与后端product_type的映射
    filterTypeMap: {
      'all': null,
      'coffeeBeans': 'coffee',
      'coffeeTools': 'merchandise'
    },
      collections: [],
      currentPage: 1, // 当前页码
      pageSize: 6, // 每页数量
      totalPages: 1, // 总页数
      totalCollections: 0, // 收藏总数
      purchasedCount: 0, // 已购买数量
      unpurchasedCount: 0, // 未购买数量
    };
  },
  computed: {
    userProfile(){
    return this.$store.state.profile
  },
    filteredCollections() {
      if (this.activeFilter === "all") {
        return this.collections;
      } else {
        return this.collections.filter(
          (item) => item.category === this.activeFilter
        );
      }
    },
    totalPages() {
      return Math.ceil(this.collections.length / this.pageSize);
    },
  },
  created() {
    this.fetchCollections();
    this.cancelCollection();
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
  },
  beforeDestroy() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  methods: {
      async addToCart(item) {

          if (this.$store.getters['user/isVisitor']) {
              this.$store.commit('user/SET_REDIRECT_PATH', this.$route.path);
              return this.$confirm(
                  '您还暂未登录，无法购买商品，是否前往登录？',
                  '提示',
                  {confirmButtonText: '是', cancelButtonText: '否', type: 'warning'}
              ).then(() => {
                  this.$router.push('/login');
              }).catch(() => {
                  this.$message.info('已取消登录');
              });
          }

          // 1. 先校验参数是否完整（避免基础错误）
          console.log("当前添加的商品信息：", item); // 打印item，确认结构
          if (!item) {
              this.$message.error("商品信息为空，无法添加");
              return;
          }

          // 2. 提取正确的商品ID和类型（关键！根据你的收藏列表item结构调整）
          // 注意：这里的字段名必须和你收藏列表返回的结构一致！
          const productId = item.product_id || item.id; // 优先用item.product_id，没有再用item.id
          const productType = item.product_type; // 必须是'coffee'或'merchandise'

          // 3. 校验类型是否合法
          const validTypes = ['coffee', 'merchandise'];
          if (!validTypes.includes(productType)) {
              this.$message.error(`商品类型错误：${productType}，必须是coffee或merchandise`);
              return;
          }

          // 4. 校验ID是否有效（必须是数字且大于0）
          if (typeof productId !== 'number' || productId <= 0) {
              this.$message.error(`商品ID无效：${productId}，必须是正整数`);
              return;
          }

          try {
              // 5. 调用后端接口（参数严格匹配后端要求）
              const response = await api.post('/cart', {
                  product_id: productId, // 确保传给后端的是正确的商品ID
                  product_type: productType, // 确保类型正确
                  quantity: 1 // 数量默认1（后端要求ge=1）
              });

              // 6. 成功处理
              alert('已成功添加至购物车');
              window.location.reload();
          } catch (error) {
          }
      },
    fetchCollections(){
      const productType = this.filterTypeMap[this.activeFilter];
      const params = {
        page: this.currentPage,
        limit: this.pageSize
      };
    // 如果不是“全部收藏”，则添加product_type参数
    if (productType !== null) {
      params.product_type = productType;
    }
      this.$axios.get('http://127.0.0.1:8000/favorite/my/page/', {
         params: params,
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`
        }
      })
     .then(response => {
        if (response.code === 200) {
          // 后端返回结构：data.favorite_list 是当前页数据，data.pagination 是分页信息
          const { favorite_list, pagination } = response.data;

          // 存储当前页收藏数据
          this.collections = favorite_list;

          // 更新分页元数据
          this.totalCollections = pagination.total; // 总收藏数
          this.totalPages = pagination.total_pages; // 总页数

          // 计算已购买/未购买数量（如果后端有提供可直接使用，否则前端计算）
          this.purchasedCount = this.collections.filter(item => item.isPurchased).length;
          this.unpurchasedCount = this.collections.length - this.purchasedCount;
        } else {
          console.error('获取收藏列表失败：', response.message);
          this.$message.error('获取收藏失败：' + response.message);
        }
      })
     .catch(error => {
        console.error('获取收藏列表出错：', error);
        if (error.response && error.response.status === 401) {
          this.$message.warning('登录已过期，请重新登录');
          this.$router.push('/login');
        } else {
          this.$message.error('网络错误，获取收藏失败');
        }
      });

    },
    cancelCollection(item) {
  this.$axios.delete('http://127.0.0.1:8000/favorite/', {
    params: {
      product_id: item.product_id,
      product_type: item.product_type
    },
    headers: {
      Authorization: `Bearer ${localStorage.getItem('token')}`
    }
  })
  .then(response => {
    if (response.code === 200) {
      // 删除成功，从收藏列表中移除该收藏项
      this.collections = this.collections.filter(collectionItem =>
        collectionItem.product_id !== item.product_id ||
        collectionItem.product_type !== item.product_type
      );
      this.$message.success('取消收藏成功');
      this.fetchCollections();
    }
  })
  .catch(error => {
    console.error('取消收藏失败:', error);
    this.$message.error('取消收藏失败');
  });
},
    handleFilter(filterValue) {
      this.activeFilter = filterValue;
      this.currentPage = 1;
      this.fetchCollections();
    },
    clearAllCollections() {
      this.$confirm('确定要清空所有收藏吗？此操作不可撤销', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 调用后端接口
      const response = await this.$axios.delete('http://127.0.0.1:8000/favorite/delete', {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`
        }
      });

      if (response.code === 200) {
        // 清空前端收藏列表
        this.collections = [];
        this.$message.success(response.message);

        // 如果需要，可以重新获取最新数据（虽然已经清空）
        // await this.fetchCollections();
      }
    } catch (error) {
      console.error('清空收藏失败:', error);
      this.$message.error('清空收藏失败，请稍后重试');
    }
  }).catch(() => {
    this.$message.info('已取消清空操作');
  });
    },
    goToPage(page) {
      if (page < 1 || page > this.totalPages || page === this.currentPage) return;
      this.currentPage = page;
      this.fetchCollections();
    },
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.fetchCollections();
      }
    },

    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
        this.fetchCollections();
      }
    },
    handleScroll() {
      this.showTop = window.scrollY > 300;
    },
    toTop() {
      window.scrollTo({ top: 0, behavior: "smooth" });
    },
  },
};

</script>
<style scoped>
/* 全局样式 */
.my-collection {
  background-color: #f9f7f5;
  min-height: 100vh;
}

/* 头部横幅 */
.hero {
  height: 200px;
  background-color: #8B5A2B;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #fff;
}

.hero h1 {
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 8px;
}

.hero p {
  font-size: 16px;
  opacity: 0.9;
}

/* 面包屑导航 */
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.breadcrumb {
  margin: 16px 0;
  font-size: 14px;
  color: #666;
}

.breadcrumb a {
  color: #8B5A2B;
  text-decoration: none;
}

.breadcrumb a:hover {
  text-decoration: underline;
}

.sep {
  margin: 0 8px;
  color: #999;
}

/* 主内容区 */
.layout {
  margin-bottom: 40px;
}

.collection-content {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

/* 用户信息与统计 */
.user-collection-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
  margin-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.user-info {
  display: flex;
  align-items: center;

}

.user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 12px;
  border: 2px solid #f0f0f0;
}

.user-details .user-name {
  font-size: 18px;
  color: #333;
  margin: 0 0 2px 0;
}

.user-details .member-level {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.collection-stats {
  display: flex;
  gap: 30px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 20px;
  font-weight: bold;
  color: #8B5A2B;
  display: block;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

/* 筛选区域 */
.filter-area {
  display: flex;
  align-items: center;
  padding: 10px 0;
  margin-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.filter-label {
  font-size: 14px;
  color: #333;
  margin-right: 12px;
}

.filter-buttons {
  display: flex;
  gap: 10px;
  margin-right: auto;
}

.filter-btn {
  padding: 6px 14px;
  border: 1px solid #ddd;
  border-radius: 16px;
  background-color: #fff;
  color: #666;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.filter-btn:hover {
  border-color: #8B5A2B;
  color: #8B5A2B;
}

.filter-btn.active {
  background-color: #8B5A2B;
  color: #fff;
  border-color: #8B5A2B;
}

.clear-all-btn {
  display: flex;
  align-items: center;
  background-color: transparent;
  border: none;
  color: #666;
  font-size: 14px;
  cursor: pointer;
  transition: color 0.2s ease;
}

.clear-all-btn:hover {
  color: #8B5A2B;
}

.clear-all-btn i {
  margin-right: 5px;
}

/* 收藏列表 */
.collections-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.collection-card {
  background-color: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
  transition: box-shadow 0.2s ease;
}

.collection-card:hover {
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.08);
}

.card-image {
  position: relative;
  height: 180px;
  overflow: hidden;
}

.card-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.collection-card:hover .card-image img {
  transform: scale(1.05);
}

.wish-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.9);
  border: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #8B5A2B;
  transition: all 0.2s ease;
}

.wish-btn:hover {
  background-color: #fff;
  transform: scale(1.1);
}

/* 卡片信息 */
.card-info {
  padding: 12px 15px;
}

.collection-title {
  font-size: 16px;
  color: #333;
  margin: 0 0 8px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.collection-desc {
  font-size: 13px;
  color: #666;
  line-height: 1.4;
  margin: 0 0 10px 0;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  height: 36px;
}

/* 价格区域：现价、原价 */
.price-area {
  display: flex;
  align-items: baseline;
  margin-bottom: 12px;
}

.now-price {
  font-size: 18px;
  font-weight: bold;
  color: #8B5A2B;
  margin-right: 8px;
}

.old-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through; /* 原价划线 */
}

.cart-btn {
  width: 100%;
  padding: 8px 0;
  background-color: #8B5A2B;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.cart-btn:hover {
  background-color: #704824;
}

/* 空状态提示 */
.empty-tip {
  text-align: center;
  padding: 50px 0;
  color: #999;
  font-size: 16px;
  grid-column: 1 / -1;
}

/* 分页样式 */
.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
  gap: 5px;
}

.pagination-btn {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #fff;
  color: #666;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.pagination-btn:hover {
  border-color: #8B5A2B;
  color: #8B5A2B;
}

.pagination-btn.active {
  background-color: #8B5A2B;
  color: #fff;
  border-color: #8B5A2B;
}

.arrow-icon {
  font-size: 12px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .user-collection-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .collection-stats {
    width: 100%;
    justify-content: space-around;
  }

  .filter-area {
    flex-wrap: wrap;
    gap: 10px;
  }

  .clear-all-btn {
    margin-left: 0;
    margin-top: 5px;
  }

  .collections-grid {
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  }
}

@media (max-width: 480px) {
  .collections-grid {
    grid-template-columns: 1fr;
  }

  .hero h1 {
    font-size: 24px;
  }

  .hero p {
    font-size: 14px;
  }
}

/* 圆形头像样式 */
.avatar-circle {
  width: 100px; /* 头像宽度，可根据需要调整 */
  height: 100px; /* 头像高度，需与宽度一致以保证圆形 */
  border-radius: 50%; /* 圆角设置为 50% 实现圆形 */
  object-fit: cover; /* 图片自适应，保持比例且填充容器 */
  display: block; /* 消除默认 inline 带来的间隙 */
  margin: 0 auto; /* 水平居中（可选，根据布局需求） */
}
    /* 针对该组件中的 router-link 链接样式重置 */
/deep/ .router-link {
  color: inherit; /* 继承父元素的颜色，恢复原来的颜色 */
  text-decoration: none; /* 去除下划线（如果需要） */
}

/* 或者直接针对 .name 类设置颜色 */
.name {
  color: #333; /* 替换成你原来的文字颜色，比如黑色 #333 或其他 */
  text-decoration: none; /* 确保没有下划线 */
}

/* 可选：如果需要去除点击后的高亮样式 */
/deep/ .router-link:active,
/deep/ .router-link:focus {
  color: inherit;
  outline: none;
}
</style>